package controller

import (
	"GO/common"
	"GO/model"
	"GO/tools"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	var json model.User_login
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": 400,
			"msg":    err,
		})
		return
	}
	if !tools.Verify(json.Account, json.Password) {
		c.JSON(http.StatusOK, gin.H{
			"status": 400,
			"msg":    "账号和密码格式有问题",
		})
		return
	}
	db := common.GetDB()
	var result model.Getdatabase
	if err := db.Raw("SELECT class, username FROM user_information WHERE account = ? AND password = ?", json.Account, json.Password).Scan(&result); err.Error != nil {
		c.JSON(http.StatusOK, gin.H{
			"status": 400,
			"msg":    "账号密码不存在",
		})
		return
	}
	//发放token
	token, err := common.ReleaseToken(json.Account, result.Username, result.Class)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status": 500,
			"err":    err,
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"status":   200,
		"class":    result.Class,
		"username": result.Username,
		"token":    token,
	})
}
